package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.request.LoginRequest;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.domain.response.UserInfo;
import com.bwie.common.exctption.BizException;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.remote.SysUserRemote;
import com.bwie.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:2891704036@qq.com">zhiyuheng</a>
 * @version 1.0
 * @description:
 * @date 2025/8/28 9:14
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private SysUserRemote sysUserRemote;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录
     * @param loginRequest
     * @return
     */
    @Override
    public JwtResponse login(LoginRequest loginRequest) {
        //手机号正则校验
        String phone = loginRequest.getPhone();
        //判断格式是否正确
        if (!phone.matches("1[3-9]\\d{9}")){
            throw new BizException("手机号格式错误");
        }
        //判断手机号和密码与数据库是否一致
        Result<UserInfo> result = sysUserRemote.findByPhoneAndPassword(loginRequest);
        //获取响应数据
        UserInfo userInfo = result.getData();
        //判空
        if (ObjectUtil.isEmpty(userInfo)){
            throw new BizException("手机号或密码错误");
        }
        //登录成功，开始存token
        Map<String,Object> map = new HashMap<>();
        //获取用户标识
        String userKey = IdUtil.randomUUID();
        //存用户标识
        map.put(JwtConstants.USER_KEY,userKey);
        //获取token
        String token = JwtUtils.createToken(map);
        //用户信息存redis
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY + userKey,userInfo,30, TimeUnit.MINUTES);
        //new一个JwtResponse
        JwtResponse jwtResponse = new JwtResponse();
        //存token
        jwtResponse.setToken(token);
        //存过期时间
        jwtResponse.setExpireTime("30MIN");
        //返回结果
        return jwtResponse;
    }
}
